<?php namespace models;
use helpers\Helper as Helper;
/**
 * This code is property of Piotr Poradzisz. Do not distribute under threat of legal consequences.
 * All rights reserved.
 * Все права защищены.
 * Alle Rechte vorbehalten.
 * Todos los derechos reservados.
 * Wszelkie prawa zastrzeżone.
 *                  جميع الحقوق محفوظة
 * 保留所有权利
 * すべての著作権
 * @author Piotr Poradzisz
 * email: piotr.poradzisz@gmail.com
 * tel.: +48668027020
 */
class Table extends Field{

    public $from;

    public $rowsPerPage = 50;

    public function setOrder($fieldId) {
        $this->setFieldProperties($fieldId, array('tableName', 'name'));
        $from = $_SESSION['query']['from'];
        if($this->tableName){
            if($this->tableName == $from){
                $string = "t1.name, $from.name";
            }
            else{
                $string = "$this->tableName.$this->name";
            }
        }
        else{
            $string = "$from.$this->name";
        }
        switch ($_SESSION['query']['order']['string']) {
            case "ORDER BY $string ASC"   :     $_SESSION['query']['order']['string'] = "ORDER BY $string DESC";
                                                break;
            case "ORDER BY $string DESC"  :
            default                       :     $_SESSION['query']['order']['string'] = "ORDER BY $string ASC";
                                                break;
        }
    }

    public function setLimit($page = 0) {
        $_SESSION['page'] = $page;
        $rowsPerPage = (isset($_SESSION['query']['rowsPerPage']) ? $_SESSION['query']['rowsPerPage'] : $this->rowsPerPage);
        $start = $rowsPerPage*$page;
        $_SESSION['query']['limit'] = "LIMIT $start, $rowsPerPage";
    }

    public function setRowsPerPage($rowsPerPage) {
        $this->rowsPerPage = $_SESSION['query']['rowsPerPage'] = $rowsPerPage;
        $this->setLimit();
    }

    public function getPagesCount() {
        $from   = (isset($_SESSION['query']['from']) ? $_SESSION['query']['from'] : null);
        $join   = (isset($_SESSION['query']['join']) ? $_SESSION['query']['join'] : null);
        $where  = (isset($_SESSION['query']['where']) ? $_SESSION['query']['where']['string'] : null);
        if($from){
            $mysql = new Mysql();
            $query = "SELECT count(*) FROM $from $join $where";
            $rowsCount = $mysql->getRecord($query);
            return ceil($rowsCount/$_SESSION['query']['rowsPerPage'])-1;
        }
        else return false;
    }

    public function getTableRows($menu = null) {
        $mysql = new Mysql();
        if($menu or !$_SESSION['query']){
            $_SESSION['query']['rowsPerPage'] = $this->rowsPerPage;
            $fields = self::getFields($menu, 'tr.row');
            if($fields){
                $relation = new Relation($_SESSION['navigation']['menu']);
                $relation->select($fields);
                $relation->join($fields);
            }            
        }
        if(isset($_SESSION['query'])){
            $select = (isset($_SESSION['query']['select'])  ? $_SESSION['query']['select']          : null);
            $from   = (isset($_SESSION['query']['from'])    ? $_SESSION['query']['from']            : null);
            $join   = (isset($_SESSION['query']['join'])    ? $_SESSION['query']['join']            : null);
            $where  = (isset($_SESSION['query']['where'])   ? $_SESSION['query']['where']['string'] : null);
            $order  = (isset($_SESSION['query']['order'])   ? $_SESSION['query']['order']['string'] : null);
            $limit  = (isset($_SESSION['query']['limit'])   ? $_SESSION['query']['limit']           : null);
        }
        
        if(isset($select) and isset($from)){
            $query = "  SELECT  $select
                        FROM    $from
                                $join
                                $where
                                $order
                                $limit ";
            $rows = $mysql->getTable($query);
            $headers = self::getFields($_SESSION['navigation']['menu'], 'tr.head');
            foreach($rows as $rowsKey => $row){
                foreach($row as $columnKey => $column){
                        $string = strip_tags($column);
                        if(strlen($string) > 128) $string = substr($string, 0, 128).'...';
                    $rows[$rowsKey][$columnKey] = $string;
                }
            }
            return $rows;

        }
        else return false;
    }
    
    public static function getTableHeaders($menu){
        $search = Search::getSearchFields($menu);
        $headers = self::getFields($menu, 'tr.head');
        foreach($headers as $headerKey => $header){
            $searchKey = Helper::multiDimensionalSearch($search, 'fieldId', $header['fieldId']);
            if($searchKey !== false) $headers[$headerKey ]['search'] = $search[$searchKey];
        }
        return $headers;
    }

    public function setTableSequence($sequence){
        $this->setSequence($_SESSION['query']['from'], $sequence);
    }
}
?>